import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/constants.dart';
import 'package:seedfour/app/theme.dart';
import 'package:seedfour/toolkit/typedef/function.dart';

import '../../../models/dictionary_entity.dart';
import 'logic.dart';

class CaseCreatePage extends StatelessWidget {
  CaseCreatePage({Key? key}) : super(key: key);

  final logic = Get.find<CaseCreateLogic>();

  @override
  Widget build(BuildContext context) {
    return Obx(
      () => Scaffold(
        appBar: AppBar(
          title: Text(logic.pageType == CaseCreatePageType.create ? '创建案件' : '利冲查询'),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              size: 16.w,
            ),
            onPressed: () {
              Get.back();
            },
          ),
        ),
        body: Form(
          key: logic.formKey,
          child: ListView(
            padding: EdgeInsets.symmetric(
              vertical: kSpaceMedium,
              horizontal: kSpaceSmall,
            ),
            children: [
              if (logic.pageType == CaseCreatePageType.query) ...[
                _buildSearch(),
              ],
              if (logic.pageType != CaseCreatePageType.query) ...[
                _buildCaseClient(),
                SizedBox(height: kSpaceMedium),
                _buildCaseOpposite(),
                SizedBox(height: kSpaceMedium),
                _buildCaseThird(),
                SizedBox(height: kSpaceMedium),
                _buildCaseTypeSelect(),
                SizedBox(height: kSpaceMedium),
                _buildRemark(),
              ],
              SizedBox(height: kSpaceMedium),
              _buildSubmitButton(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildSearch() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(kRadiusSmall),
        color: Colors.white,
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Autocomplete<String>(
            optionsBuilder: (TextEditingValue value) {
              logic.getCompanyInfo(value.text, logic.searchCaseCodeController);
              logic.searchCaseNameController.value = value;
              return logic.searchOrg(value.text);
            },
            onSelected: (value) {
              logic.searchCaseNameController.text = value;
              logic.getCompanyInfo(value, logic.searchCaseCodeController);
            },
            fieldViewBuilder:
                (context, controller, focusNode, onFieldSubmitted) {
              return Padding(
                padding: EdgeInsets.symmetric(horizontal: kSpaceMini),
                child: TextFormField(
                  style: TextStyle(
                    fontSize: kFontSizeSmall,
                    color: AppColor.colorFontBlack,
                  ),
                  controller: logic.searchCaseNameController,
                  focusNode: focusNode,
                  decoration: InputDecoration(
                    hintText: '请输入名称进行查询',
                    hintStyle: TextStyle(
                      color: AppColor.colorFontLabelGrey,
                      fontSize: kFontSizeSmall,
                    ),
                    border: InputBorder.none,
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请输入名称';
                    }
                    return null;
                  },
                  onChanged: (value) {
                    controller.value = TextEditingValue(text: value);
                  },
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildSubmitButton() {
    return Container(
      height: 50.w,
      padding: EdgeInsets.symmetric(horizontal: kSpaceSmall),
      child: FilledButton(
        onPressed: logic.isCreating.value
            ? null
            : () {
                if (logic.formKey.currentState!.validate()) {
                  logic.formKey.currentState!.save();
                  logic.createCase();
                }
              },
        child: Text(logic.pageType != CaseCreatePageType.query ? '创建' : '开始查询'),
      ),
    );
  }

  Widget _buildRemark() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(kRadiusSmall),
        color: Colors.white,
      ),
      padding: EdgeInsets.all(kSpaceSmall),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '备注',
            style: TextStyle(fontSize: kFontSizeLarge),
          ),
          SizedBox(height: kSpaceMini),
          TextFormField(
            controller: logic.remarkController,
            maxLines: 5,
            decoration: InputDecoration(
              border: InputBorder.none,
              hintText: '请输入备注',
              hintStyle: TextStyle(
                fontSize: kFontSizeSmall,
                color: AppColor.colorFontLabelGrey,
              ),
            ),
          ),
        ],
      ),
    );
  }

  List<Widget> _buildBusiness() {
    return logic.caseType.value == CaseType.nonLawsuit
        ? [
            SizedBox(height: kSpaceLarge),
            Text(
              '选择行业和分类',
              style: TextStyle(fontSize: kFontSizeLarge),
            ),
            SizedBox(height: kSpaceMini),
            Text(
              '若是常法，在所属分类中选择 E.公司合规及常年',
              style: TextStyle(
                fontSize: kFontSizeMini,
                color: AppColor.colorFontGrey,
              ),
            ),
            SizedBox(height: kSpaceMedium),
            Text(
              '*所属行业',
              style: TextStyle(
                fontSize: kFontSizeSmall,
                color: AppColor.colorFontBlack,
              ),
            ),
            DropdownButtonFormField2<DictionaryEntity>(
              value: logic.caseBusinessType.value,
              iconStyleData: const IconStyleData(
                  icon: Icon(
                Icons.keyboard_arrow_down_rounded,
                color: AppColor.colorFontBlack,
              )),
              decoration: InputDecoration(
                hintText: '请选择',
                hintStyle: TextStyle(
                  fontSize: kFontSizeSmall,
                  color: AppColor.colorFontLabelGrey,
                  fontWeight: AppFont.fontRegular,
                ),
                border: InputBorder.none,
              ),
              dropdownStyleData: const DropdownStyleData(
                padding: EdgeInsets.all(0),
                elevation: 0,
                decoration: BoxDecoration(
                  border: Border.fromBorderSide(
                    BorderSide(color: Color(0xFFE3E6EB)),
                  ),
                  borderRadius: BorderRadius.all(Radius.circular(4)),
                  color: Colors.white,
                ),
              ),
              style: TextStyle(
                color: AppColor.colorFontBlack,
                fontSize: kFontSizeSmall,
                fontWeight: AppFont.fontRegular,
              ),
              validator: (value) {
                if (logic.caseType.value == CaseType.nonLawsuit &&
                    value == null) {
                  return '所属行业不能为空！';
                }
                return null;
              },
              onChanged: (value) => logic.caseBusinessType.value = value!,
              items: logic.caseBusinessTypes.map((e) {
                return DropdownMenuItem<DictionaryEntity>(
                  value: e,
                  child: Text(
                    e.value!,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: AppColor.colorFontBlack,
                      fontSize: kFontSizeSmall,
                      fontWeight: AppFont.fontRegular,
                    ),
                  ),
                );
              }).toList(),
            ),
            SizedBox(height: kSpaceSmall),
            Text(
              '*所属分类',
              style: TextStyle(
                fontSize: kFontSizeSmall,
                color: AppColor.colorFontBlack,
              ),
            ),
            DropdownButtonFormField2<DictionaryEntity>(
              value: logic.caseClassType.value,
              isExpanded: true,
              iconStyleData: const IconStyleData(
                  icon: Icon(
                Icons.keyboard_arrow_down_rounded,
                color: AppColor.colorFontBlack,
              )),
              decoration: InputDecoration(
                hintText: '请选择',
                hintStyle: TextStyle(
                  fontSize: kFontSizeSmall,
                  color: AppColor.colorFontLabelGrey,
                  fontWeight: AppFont.fontRegular,
                ),
                border: InputBorder.none,
              ),
              dropdownStyleData: const DropdownStyleData(
                padding: EdgeInsets.all(0),
                elevation: 0,
                decoration: BoxDecoration(
                  border: Border.fromBorderSide(
                    BorderSide(color: Color(0xFFE3E6EB)),
                  ),
                  borderRadius: BorderRadius.all(Radius.circular(4)),
                  color: Colors.white,
                ),
              ),
              style: TextStyle(
                color: AppColor.colorFontBlack,
                fontSize: kFontSizeSmall,
                fontWeight: AppFont.fontRegular,
              ),
              validator: (value) {
                if (logic.caseType.value == CaseType.nonLawsuit &&
                    value == null) {
                  return '所属分类不能为空！';
                }
                return null;
              },
              onChanged: (value) => logic.caseClassType.value = value!,
              items: logic.caseClassTypes.map((e) {
                return DropdownMenuItem<DictionaryEntity>(
                  value: e,
                  child: Text(
                    e.value!,
                    style: TextStyle(
                      color: AppColor.colorFontBlack,
                      fontSize: kFontSizeSmall,
                      fontWeight: AppFont.fontRegular,
                    ),
                  ),
                );
              }).toList(),
            ),
          ]
        : [];
  }

  List<Widget> _buildCaseNameField() {
    return logic.caseType.value != null &&
            logic.caseType.value != CaseType.nonLawsuit
        ? [
            SizedBox(height: kSpaceLarge),
            Text(
              '案件原由或罪名(诉讼)',
              style: TextStyle(fontSize: kFontSizeMedium),
            ),
            SizedBox(height: kSpaceSmall),
            TextFormField(
              controller: logic.caseNameController,
              maxLines: 5,
              decoration: InputDecoration(
                border: InputBorder.none,
                hintText: '案由填写遵照最高法案由规定',
                hintStyle: TextStyle(
                  fontSize: kFontSizeSmall,
                  color: AppColor.colorFontLabelGrey,
                ),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入案件原由';
                }
                return null;
              },
            ),
          ]
        : [];
  }

  List<Widget> _buildLawsuitTypeSelect() {
    return logic.caseType.value == CaseType.lawsuit
        ? [
            SizedBox(height: kSpaceLarge),
            Text(
              '刑事/非刑事',
              style: TextStyle(fontSize: kFontSizeMedium),
            ),
            SizedBox(height: kSpaceSmall),
            Wrap(
              spacing: 6.w,
              runSpacing: kSpaceSmall,
              children: [
                _buildSelectionBtn(
                  LawsuitType.criminal.label,
                  LawsuitType.criminal.value,
                  logic.lawsuitType.value == LawsuitType.criminal,
                  onTap: () => logic.lawsuitType.value = LawsuitType.criminal,
                ),
                _buildSelectionBtn(
                  LawsuitType.civil.label,
                  LawsuitType.civil.value,
                  logic.lawsuitType.value == LawsuitType.civil,
                  onTap: () => logic.lawsuitType.value = LawsuitType.civil,
                ),
                _buildSelectionBtn(
                  LawsuitType.administration.label,
                  LawsuitType.administration.value,
                  logic.lawsuitType.value == LawsuitType.administration,
                  onTap: () =>
                      logic.lawsuitType.value = LawsuitType.administration,
                ),
                _buildSelectionBtn(
                  LawsuitType.arbitration.label,
                  LawsuitType.arbitration.value,
                  logic.lawsuitType.value == LawsuitType.arbitration,
                  onTap: () =>
                      logic.lawsuitType.value = LawsuitType.arbitration,
                ),
              ],
            ),
          ]
        : [];
  }

  Widget _buildCaseTypeSelect() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(kRadiusSmall),
        color: Colors.white,
      ),
      padding: EdgeInsets.all(kSpaceSmall),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Text(
            '案件类型',
            style: TextStyle(fontSize: kFontSizeMedium),
          ),
          SizedBox(height: kSpaceSmall),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              _buildSelectionBtn(
                CaseType.lawsuit.label,
                CaseType.lawsuit.value,
                logic.caseType.value == CaseType.lawsuit,
                onTap: () => logic.caseType.value = CaseType.lawsuit,
              ),
              _buildSelectionBtn(
                CaseType.nonLawsuit.label,
                CaseType.nonLawsuit.value,
                logic.caseType.value == CaseType.nonLawsuit,
                onTap: () => logic.caseType.value = CaseType.nonLawsuit,
              ),
              _buildSelectionBtn(
                CaseType.arbitration.label,
                CaseType.arbitration.value,
                logic.caseType.value == CaseType.arbitration,
                onTap: () => logic.caseType.value = CaseType.arbitration,
              ),
            ],
          ),
          ..._buildLawsuitTypeSelect(),
          ..._buildCaseNameField(),
          ..._buildBusiness(),
          SizedBox(height: kSpaceSmall),
        ],
      ),
    );
  }

  // 构建单选按钮
  Widget _buildSelectionBtn(String title, String value, bool selected,
      {ParamVoidCallback? onTap}) {
    return Container(
      width: 100.w,
      decoration: BoxDecoration(
        border: Border.all(
          color: selected ? AppColor.colorFontBlue : Colors.transparent,
        ),
        color: selected ? const Color(0xFFF2F3FF) : const Color(0xFFF4F6F9),
        borderRadius: BorderRadius.circular(kRadiusSmall),
      ),
      padding: EdgeInsets.symmetric(
        vertical: kSpaceMini,
        horizontal: kSpaceMedium,
      ),
      child: InkWell(
        onTap: onTap,
        child: Text(
          title,
          textAlign: TextAlign.center,
          style: TextStyle(
            color: selected ? AppColor.colorFontBlue : AppColor.colorFontGrey,
            fontSize: kFontSizeMedium,
          ),
        ),
      ),
    );
  }

  Widget _buildCaseThird() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(kRadiusSmall),
        color: Colors.white,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.all(kSpaceMedium),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '第三方信息',
                  style: TextStyle(fontSize: kFontSizeMedium),
                ),
                Switch(
                    value: logic.hasThird.value,
                    onChanged: (value) => logic.setNotThirdList(value)),
              ],
            ),
          ),
          const Divider(),
          ...List.generate(
            logic.caseThirdTexts.length,
            (index) => _buildLegalPerson(
              index,
              '利益相对方',
              logic.caseThirdTexts[index],
              (index) => {logic.caseThirdTexts.removeAt(index)},
            ),
          ),
          if (logic.hasThird.value) ...[
            const Divider(),
            FilledButton(
              onPressed: () => {
                logic.caseThirdTexts.add(LegalPersonController(
                    TextEditingController(), TextEditingController()))
              },
              style: FilledButton.styleFrom(
                elevation: 0,
                foregroundColor: AppColor.colorFontBlue,
                backgroundColor: Colors.transparent,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(kRadiusMedium),
                    bottomRight: Radius.circular(kRadiusMedium),
                  ),
                ),
              ),
              child: const Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.add),
                  Text('添加第三方'),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildCaseOpposite() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(kRadiusSmall),
        color: Colors.white,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.all(kSpaceMedium),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '利益相对方信息',
                  style: TextStyle(fontSize: kFontSizeMedium),
                ),
                Switch(
                    value: logic.hasOpposite.value,
                    onChanged: (value) => logic.setNotCaseOpposite(value)),
              ],
            ),
          ),
          const Divider(),
          ...List.generate(
            logic.caseOppositeTexts.length,
            (index) => _buildLegalPerson(
              index,
              '利益相对方',
              logic.caseOppositeTexts[index],
              (index) => {logic.caseOppositeTexts.removeAt(index)},
            ),
          ),
          if (logic.hasOpposite.value) ...[
            const Divider(),
            FilledButton(
              onPressed: () => {
                logic.caseOppositeTexts.add(LegalPersonController(
                    TextEditingController(), TextEditingController()))
              },
              style: FilledButton.styleFrom(
                elevation: 0,
                foregroundColor: AppColor.colorFontBlue,
                backgroundColor: Colors.transparent,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(kRadiusMedium),
                    bottomRight: Radius.circular(kRadiusMedium),
                  ),
                ),
              ),
              child: const Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.add),
                  Text('添加利益相对方'),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildCaseClient() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(kRadiusMedium),
        color: Colors.white,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.all(kSpaceMedium),
            child: Text(
              '委托人信息',
              style: TextStyle(fontSize: kFontSizeMedium),
            ),
          ),
          const Divider(),
          ...List.generate(
            logic.caseClientTexts.length,
            (index) => _buildLegalPerson(
              index,
              '委托人',
              logic.caseClientTexts[index],
              (index) => {logic.caseClientTexts.removeAt(index)},
            ),
          ),
          const Divider(),
          FilledButton(
            onPressed: () => {
              logic.caseClientTexts.add(LegalPersonController(
                  TextEditingController(), TextEditingController()))
            },
            style: FilledButton.styleFrom(
              elevation: 0,
              foregroundColor: AppColor.colorFontBlue,
              backgroundColor: Colors.transparent,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(kRadiusMedium),
                  bottomRight: Radius.circular(kRadiusMedium),
                ),
              ),
            ),
            child: const Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.add),
                Text('添加委托人'),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildLegalPerson(
      int index,
      String title,
      LegalPersonController personController,
      ParamSingleCallback<int> callback) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: kSpaceMedium),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          index > 0 ? const Divider() : const SizedBox(),
          SizedBox(height: kSpaceSmall),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '$title${index + 1}',
                style: TextStyle(
                  fontSize: kFontSizeSmall,
                  color: AppColor.colorFontBlack,
                ),
              ),
              SizedBox(width: kSpaceMedium),
              Expanded(
                child: Autocomplete<String>(
                  optionsBuilder: (TextEditingValue value) {
                    logic.getCompanyInfo(
                        value.text, personController.codeController);
                    return logic.searchOrg(value.text);
                  },
                  onSelected: (value) {
                    logic.getCompanyInfo(
                        value, personController.codeController);
                    personController.nameController.text = value;
                  },
                  fieldViewBuilder:
                      (context, controller, focusNode, onFieldSubmitted) {
                    return TextFormField(
                      style: TextStyle(
                        fontSize: kFontSizeSmall,
                        color: AppColor.colorFontBlack,
                      ),
                      textAlign: TextAlign.end,
                      controller: personController.nameController,
                      focusNode: focusNode,
                      decoration: InputDecoration(
                        hintText: '请输入名称',
                        hintStyle: TextStyle(
                          color: AppColor.colorFontLabelGrey,
                          fontSize: kFontSizeSmall,
                        ),
                        border: InputBorder.none,
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入名称';
                        }
                        return null;
                      },
                      onChanged: (value) {
                        controller.value = TextEditingValue(text: value);
                      },
                    );
                  },
                ),
              ),
              index > 0
                  ? IconButton(
                      onPressed: () => callback(index),
                      icon: SvgPicture.asset(
                        'assets/icons/ic_cancel.svg',
                        width: 20.w,
                        height: 20.w,
                      ),
                    )
                  : const SizedBox(),
            ],
          ),
          SizedBox(height: kSpaceSmall),
          Text(
            '社会信用代码/身份证号',
            style: TextStyle(
              fontSize: kFontSizeSmall,
              color: AppColor.colorFontBlack,
            ),
          ),
          SizedBox(height: kSpaceSmall),
          TextFormField(
            controller: personController.codeController,
            decoration: InputDecoration(
              hintText: '请输入号码',
              hintStyle: TextStyle(
                color: AppColor.colorFontLabelGrey,
                fontSize: kFontSizeSmall,
              ),
              border: InputBorder.none,
            ),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '社会信用代码/身份证号';
              }
              return null;
            },
          ),
          SizedBox(height: kSpaceSmall),
        ],
      ),
    );
  }
}
